#ifndef __HMC5883L_H
#define __HMC5883L_H

#include "wire.h"
#include <stdint.h>

// HMC5883L I2C 地址
#define HMC5883L_ADDR_DEFAULT   0x1E

// 寄存器地址
#define HMC5883L_REG_CONFIG_A   0x00
#define HMC5883L_REG_CONFIG_B   0x01
#define HMC5883L_REG_MODE       0x02
#define HMC5883L_REG_DATA_X_H   0x03
#define HMC5883L_REG_STATUS     0x09

// 模式设置
#define HMC5883L_MODE_CONT      0x00
#define HMC5883L_MODE_SINGLE    0x01
#define HMC5883L_MODE_IDLE      0x03

//速率配置
#define HMC5883L_RATE_0_75HZ    0
#define HMC5883L_RATE_1_5HZ     1
#define HMC5883L_RATE_3HZ       2
#define HMC5883L_RATE_7_5HZ     3
#define HMC5883L_RATE_15HZ      4
#define HMC5883L_RATE_30HZ      5
#define HMC5883L_RATE_75HZ      6
#define HMC5883L_RATE_150HZ     7


// 默认配置值
#define HMC5883L_DEFAULT_SAMPLES    0x03    // 8 samples average
#define HMC5883L_DEFAULT_RANGE      0x20    // Gain: 1.3 Ga (sensitivity ~1090 LSB/Gauss)
#define HMC5883L_DEFAULT_RATE   HMC5883L_RATE_75HZ

// 状态码
typedef enum {
    HMC5883L_OK = 0,
    HMC5883L_ERROR,
    HMC5883L_ERROR_DEV_NOT_FOUND,
    HMC5883L_ERROR_COMM
} HMC5883L_Status;

// 磁力计数据结构
typedef struct {
    int16_t x;
    int16_t y;
    int16_t z;
} HMC5883L_MagData;

// HMC5883L 设备对象
typedef struct {
    Wire* wire;           // 使用的 I2C 总线
    uint8_t addr;         // I2C 地址
    uint8_t mode;         // 当前模式
    float   scale;        // 灵敏度 (LSB/Gauss)
} HMC5883L;

// 初始化与配置
HMC5883L_Status HMC5883L_Init(HMC5883L* dev, Wire* wire, uint8_t addr);
HMC5883L_Status HMC5883L_Config(HMC5883L* dev, uint8_t samples, uint8_t range, uint8_t rate);
HMC5883L_Status HMC5883L_SetMode(HMC5883L* dev, uint8_t mode);

// 数据读取
HMC5883L_Status HMC5883L_ReadRaw(HMC5883L* dev, HMC5883L_MagData* data);
HMC5883L_Status HMC5883L_ReadScaled(HMC5883L* dev, float* x, float* y, float* z); // 单位：Gauss

// 获取设备ID（用于验证通信）
HMC5883L_Status HMC5883L_GetID(HMC5883L* dev, uint8_t* id);

// 内部辅助函数
HMC5883L_Status HMC5883L_WriteReg(HMC5883L* dev, uint8_t reg, uint8_t value);
HMC5883L_Status HMC5883L_ReadRegs(HMC5883L* dev, uint8_t reg, uint8_t* buf, uint8_t len);

#endif
/*
// 初始化 HMC5883L
    if (HMC5883L_Init(&sensor, &wire, HMC5883L_ADDR_DEFAULT) != HMC5883L_OK) {
		printf("device not found\n");
        // 错误处理：设备未找到或通信失败
        while(1);
    }
	HMC5883L_SetMode(&sensor, HMC5883L_MODE_CONT);
	delay_ms(100);

    HMC5883L_MagData raw;
    float x, y, z;

    while (1) {
        if (HMC5883L_ReadRaw(&sensor, &raw) == HMC5883L_OK) {
			printf("raw: %d %d %d\n",raw.x, raw.y, raw.z);
            // 使用 raw.x, raw.y, raw.z
        }

        if (HMC5883L_ReadScaled(&sensor, &x, &y, &z) == HMC5883L_OK) {
			printf("%.2f %.2f %.2f\n",x, y, z );
            // x, y, z 单位为 Gauss
        }

        delay_ms(100);
    }
*/
